from tortoise import fields
from pydantic.types import Decimal

from zhenxun.services.log import logger
from zhenxun.services.db_context import Model


class StockDB(Model):
    id = fields.IntField(pk=True, generated=True, auto_increment=True)
    uid = fields.CharField(max_length=255, null=False)
    stock_id = fields.CharField(max_length=255, null=False)
    number = fields.DecimalField(max_digits=10, decimal_places=3, null=True)
    buy_time = fields.DatetimeField(auto_now_add=True)
    gearing = fields.DecimalField(max_digits=10, decimal_places=3, null=True, default=1)
    cost = fields.DecimalField(max_digits=10, decimal_places=3, null=True)

    class Meta:
        table = "stock_game"
        table_description = "股海风云·股票表"

    @classmethod
    async def buy_stock(
        cls, uid: str, stock_id: str, gearing: float, number: Decimal, cost: Decimal
    ) -> "StockDB":
        try:
            query = await cls.filter(uid=uid, stock_id=stock_id).first()
            if not query:
                logger.info("第一次买")
                await cls.create(
                    uid=uid,
                    stock_id=stock_id,
                    gearing=gearing,
                    number=number,
                    cost=cost,
                )
            else:
                logger.info("已经买过了")
                query.number = number + query.number
                query.cost = cost + query.cost
                await query.save()
            return await cls.filter(uid=uid, stock_id=stock_id).first()
        except Exception as e:
            logger.info(f"购买股票数据库问题 {type(e)}: {e}")
            raise e

    @classmethod
    async def sell_stock(cls, uid: str, stock_id: str, percent: float) -> None:
        try:
            query = await cls.filter(uid=uid, stock_id=stock_id).first()
            if not query:
                logger.error("错误 这个股票不存在")
            else:
                logger.info("正在卖股票")
                if percent != 10:
                    query.number = query.number * (1 - Decimal(percent) / 10)
                    query.cost = query.cost * (1 - Decimal(percent) / 10)
                    await query.save()
                else:
                    await query.delete()
        except Exception as e:
            # do something with the traceback string
            logger.info(f"销售股票数据库问题 {type(e)}: {e}")
            raise e

    @classmethod
    async def get_stock(cls, uid: str, stock_id: str) -> "StockDB":
        try:
            return await cls.filter(uid=uid, stock_id=stock_id).first()
        except Exception as e:
            logger.info(f"单个查询股票数据库问题 {type(e)}: {e}")
            raise e

    @classmethod
    async def get_my_stock(
        cls,
        uid: str,
    ) -> list["StockDB"]:
        try:
            return await cls.filter(uid=uid).all()
        except Exception as e:
            logger.info(f"单个查询股票数据库问题 {type(e)}: {e}")
            raise e

    @classmethod
    async def clear_stock_by_id(cls, uid: str, stock_id: str) -> None:
        try:
            await cls.filter(uid=uid, stock_id=stock_id).delete()
        except Exception as e:
            logger.info(f"删除指定股票问题 {type(e)}: {e}")
            raise e

    @classmethod
    async def get_stocks_by_uid(
        cls,
        uid: str,
    ) -> list["StockDB"]:
        try:
            return await cls.filter(uid=uid).all()
        except Exception as e:
            logger.info(f"批量查询股票数据库问题 {type(e)}: {e}")
            raise e
